package com.gxa.xc.rbac.interceptor;

import com.gxa.xc.rbac.exception.PermissionJsonException;
import com.gxa.xc.rbac.exception.PermissionPageException;
import com.gxa.xc.rbac.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 权限拦截器
 * @author:IT-CNLM
 * @date:Created at 2020/10/27
 */
public class PermissionInterceptor implements HandlerInterceptor {


    @Autowired
    private MenuService menuService;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 先去获取当前登陆用户 得角色
        if (menuService.isSuper(request.getSession())) {
            // 是超级管理员
            return true;
        }
        // 非超级管理员
        // 获取当前请求得URL
        String url = request.getServletPath();
        // 和当前登陆用户所拥有得权限进行对比
        if (menuService.hasPermission(request.getSession(), url)) {
            // 有权限
            return true;
        }

        // 判断是否是ajax请求
        // ajax请求 应该返回json
        // 如果是同步请求 应该返回页面
        if (isAjaxRequest(request)) {
            throw new PermissionJsonException(1009, "对不起, 长得漂亮的才能访问!");
        }

        //抛出异常
        throw new PermissionPageException(1009, "对不起,不让你访问!");
    }


    /**
     * 判断是否是ajax请求
     * @param request
     * @return
     */
    private Boolean isAjaxRequest(HttpServletRequest request){
        // 先获取请求头  X-Requested-With
        String header = request.getHeader("X-Requested-With");
        if(header != null && header.equals("XMLHttpRequest")){
            // 这是一个ajax请求
            return true;
        }
        return false;
    }



}
